//
//  MineInfoViewController.m
//  copyrightTrading
//
//  Created by 郭子一 on 2020/10/7.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "MineInfoViewController.h"
#import "MineInfoAvatorCell.h"
#import "MineSettingOneCell.h"
#import "MineSettingTwoCell.h"
@interface MineInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIPickerView *pickView;
@property (nonatomic, strong) UIButton *ensureBtn;
@property (nonatomic, strong) UIButton *ensureBtn1;
@property (nonatomic, assign) NSInteger pickViewType; // 1行业 2地区

@property (nonatomic, strong) UIImage *avatorImg; // 1行业
@property (nonatomic, copy) NSString *avatorString; // 1行业
@property (nonatomic, copy) NSString *nickNameString; //
@property (nonatomic, copy) NSString *ageString; // 1行业
@property (nonatomic, copy) NSString *sexString; // 1行业
@property (nonatomic, copy) NSString *professionString; // 1行业
@property (nonatomic, copy) NSString *professionNameString; // 1行业
@property (nonatomic, copy) NSString *districtString; // 1行业
@property (nonatomic, copy) NSString *districtNameString; // 1行业
@property (nonatomic, copy) NSString *emailString; // 1行业
@property (nonatomic, strong) NSMutableDictionary *userAvatorDic; // 用户信息
@end

@implementation MineInfoViewController

- (NSMutableDictionary *)userAvatorDic
{
    if (!_userAvatorDic) {
        _userAvatorDic = [NSMutableDictionary dictionary];
    }
    return _userAvatorDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)setupUI
{
    self.view.backgroundColor = RGB_VALUE(0xF5F5F5);
    UIView *headerView = [UIView new];
    headerView.backgroundColor = RGB_VALUE(0xDC0000);
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.mas_equalTo(Height_NavBar);
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"whiteBack"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setHitEdgeInsets:UIEdgeInsetsMake(-15, -15, -15, -15)];
    [headerView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-14);
        make.left.offset(18);
        make.width.height.mas_equalTo(16);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"我的信息";
    titleLabel.font = JSS_MEDIUM_FONT(17);
    titleLabel.textColor = RGB_VALUE(0xFFFFFF);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-9);
        make.centerX.offset(0);
        make.width.mas_equalTo(135);
        make.height.mas_equalTo(24);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[MineSettingOneCell class] forCellReuseIdentifier:@"MineSettingOneCell"];
    [_tableView registerClass:[MineSettingTwoCell class] forCellReuseIdentifier:@"MineSettingTwoCell"];
    [_tableView registerClass:[MineInfoAvatorCell class] forCellReuseIdentifier:@"MineInfoAvatorCell"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(headerView.mas_bottom).offset(0);
        make.height.mas_equalTo(308);
    }];

    self.pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight - TabbarSafeBottomMargin - 300 - 20, kDeviceWidth, 300)];
    self.pickView.delegate = self;
    self.pickView.dataSource = self;
    [self.view addSubview:self.pickView];
    
    self.ensureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.ensureBtn.backgroundColor = RGB_VALUE(0xDC0000);
    [self.ensureBtn setTitle:@"确定" forState:UIControlStateNormal];
    self.ensureBtn.layer.masksToBounds = YES;
    self.ensureBtn.layer.cornerRadius = 15;
//    [self.ensureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.ensureBtn addTarget:self action:@selector(ensureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.ensureBtn];
    [self.ensureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-20);
        make.left.offset(18);
        make.right.offset(-18);
        make.height.mas_equalTo(50);
    }];
    
    self.pickView.hidden = YES;
    self.ensureBtn.hidden = YES;
    
    self.ensureBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.ensureBtn1.backgroundColor = RGB_VALUE(0xDC0000);
    [self.ensureBtn1 setTitle:@"确定" forState:UIControlStateNormal];
    self.ensureBtn1.layer.masksToBounds = YES;
    self.ensureBtn1.layer.cornerRadius = 15;
//    [self.ensureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.ensureBtn1 addTarget:self action:@selector(ensureBtn1Click) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.ensureBtn1];
    [self.ensureBtn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-20);
        make.left.offset(18);
        make.right.offset(-18);
        make.height.mas_equalTo(50);
    }];
}

- (void)ensureBtnClick
{
    self.pickView.hidden = YES;
    self.ensureBtn.hidden = YES;
    self.ensureBtn1.hidden = YES;
    [self.tableView reloadData];
}

- (void)ensureBtn1Click
{
    NSDictionary *paramDic = @{
        @"nickname":self.nickNameString,
        @"age":self.ageString,
        @"sex":self.sexString,
        @"industry":self.professionString,
        @"district":self.districtString,
        @"email":self.emailString,
    };
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypePost URLString:@"user" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [self showMessage:responseObject[@"message"]];
        [self pop];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.pickViewType == 1 ? self.indsutryList.count : self.districtList.count;
}

// 返回每行的标题
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return self.pickViewType == 1 ? self.indsutryList[row][@"title"] : self.districtList[row][@"name"];
}

// 选中行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (self.pickViewType == 1) {
        self.professionString = [NSString stringWithFormat:@"%@",self.indsutryList[row][@"id"]];
        self.professionNameString = [NSString stringWithFormat:@"%@",self.indsutryList[row][@"title"]];
    } else {
        self.districtString = [NSString stringWithFormat:@"%@",self.districtList[row][@"id"]];
        self.districtNameString = [NSString stringWithFormat:@"%@",self.districtList[row][@"name"]];
    }
}

- (void)backBtnClick
{
    [self pop];
}

// 退出登录
- (void)loginBtnClick
{
    
}

- (void)setUserInfo:(NSDictionary *)userInfo
{
    _userInfo = userInfo;
    self.avatorString = userInfo[@"head_img"];
    self.nickNameString = userInfo[@"nickname"];
    self.ageString = userInfo[@"age"];
    self.sexString = userInfo[@"sex"];
    self.professionNameString = userInfo[@"industry_name"];
    self.districtNameString = userInfo[@"district_name"];
    self.professionString = userInfo[@"industry"];
    self.districtString = userInfo[@"district"];
    self.emailString = userInfo[@"email"];
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5) {
        MineSettingOneCell *cell = [MineSettingOneCell cellWithTableView:tableView];
        if (indexPath.row == 2) {
            cell.titleLabel.text = @"年龄";
            cell.contentLabel.text = self.ageString;
        } else if (indexPath.row == 3) {
            cell.titleLabel.text = @"性别";
            cell.contentLabel.text = self.sexString;
        } else if (indexPath.row == 4) {
            cell.titleLabel.text = @"行业";
            cell.contentLabel.text = self.professionNameString;
        } else if (indexPath.row == 5) {
            cell.titleLabel.text = @"地区";
            cell.contentLabel.text = self.districtNameString;
        }
        cell.contentLabel.textColor = RGB_VALUE(0xA0A0A0);
        return cell;
    } else if (indexPath.row == 0 ){
        MineInfoAvatorCell *cell = [MineInfoAvatorCell cellWithTableView:tableView];
        cell.titleLabel.text = @"修改头像";
        [cell.avatorImg m_setImageWithUrlString:self.avatorString placeholder:@"MineHeaderImg"];
        return cell;
    } else if (indexPath.row == 1 || indexPath.row == 6 ){
        MineSettingTwoCell *cell = [MineSettingTwoCell cellWithTableView:tableView];
        if (indexPath.row == 1) {
            cell.titleLabel.text = @"昵称";
            cell.contentLabel.text = self.nickNameString;
        } else if (indexPath.row == 6) {
            cell.titleLabel.text = @"电子邮箱";
            cell.contentLabel.text = self.emailString;
        }
        cell.contentLabel.textColor = RGB_VALUE(0xA0A0A0);
        
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) { // 头像
        self.pickView.hidden = YES;
        self.ensureBtn.hidden = YES;
        self.ensureBtn1.hidden = NO;
        [self popImagePicker];
    } else if (indexPath.row == 1) { // 昵称
        self.pickView.hidden = YES;
        self.ensureBtn.hidden = YES;
        self.ensureBtn1.hidden = NO;
        [self showNickNameAlert];
    } else if (indexPath.row == 2) { // 年龄
        self.pickView.hidden = YES;
        self.ensureBtn.hidden = YES;
        self.ensureBtn1.hidden = NO;
        [self showAgeAlert];
    } else if (indexPath.row == 3) { // 性别
        self.pickView.hidden = YES;
        self.ensureBtn.hidden = YES;
        self.ensureBtn1.hidden = NO;
        [self showSexAlert];
    } else if (indexPath.row == 4) { // 行业
        self.pickView.hidden = NO;
        self.ensureBtn.hidden = NO;
        self.ensureBtn1.hidden = YES;
        [self showProfessionAlert];
    } else if (indexPath.row == 5) { // 地区
        self.pickView.hidden = NO;
        self.ensureBtn.hidden = NO;
        self.ensureBtn1.hidden = YES;
        [self showDistricAlert];
    } else if (indexPath.row == 6) { // 电子邮箱
        self.pickView.hidden = YES;
        self.ensureBtn.hidden = YES;
        self.ensureBtn1.hidden = NO;
        [self showEmailAlert];
    }
}

- (void)popImagePicker{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.editing = YES;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"选择头像来源" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    //相机选项
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //选择相机时，设置UIImagePickerController对象相关属性
        imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        //            imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        //跳转到UIImagePickerController控制器弹出相机
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    //相册选项
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //选择相册时，设置UIImagePickerController对象相关属性
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //跳转到UIImagePickerController控制器弹出相册
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    //取消按钮
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    //添加各个按钮事件
    [alert addAction:camera];
    [alert addAction:photo];
    [alert addAction:cancel];
    
    //弹出sheet提示框
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取到图片
    UIImage * image = [info valueForKey:UIImagePickerControllerEditedImage];
    [self.userAvatorDic setValue:image forKey:@"img"];
    
    [[APIManager sharedNetManager] createOrderWithParams:self.userAvatorDic success:^(NSInteger code, NSDictionary * _Nonnull dict) {
        if (code == 200) {
            [self showMessage:dict[@"message"]];
            self.avatorString = dict[@"data"];
            [self.tableView reloadData];
        }
    } failure:^(NSInteger code, NSError * _Nonnull error) {
        
    }];
    
//    NSString *str = [self imageToString:image];
//    NSArray *files = [NSArray arrayWithObjects:str, nil];
//    self.avatorString = str;
//    [self.tableView reloadData];
}
//图片转码
- (NSString *)imageToString:(UIImage *)image{
    NSData* pictureData = UIImageJPEGRepresentation(image,0.5);//进行图片压缩从0.0到1.0（0.0表示最大压缩，质量最低);
    NSString* pictureDataString = [pictureData base64EncodedString];//图片转码成为base64Encoding，
    return pictureDataString;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 昵称
- (void)showNickNameAlert
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请输入您的昵称" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *userNameTextField = alertController.textFields.firstObject;
        weakSelf.nickNameString = userNameTextField.text;
        [weakSelf.tableView reloadData];
//        [weakSelf.tableView reloadRow:1 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
    }]];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField*_Nonnull textField) {
        textField.placeholder=@"请输入您的昵称";
    }];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 年龄
- (void)showAgeAlert
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请输入您的年龄" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alertController.textFields.firstObject;
        weakSelf.ageString = textField.text;
        [weakSelf.tableView reloadData];
    }]];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField*_Nonnull textField) {
        textField.placeholder=@"请输入您的年龄";
    }];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 性别
- (void)showSexAlert
{
    __weak typeof(self) weakSelf = self;
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * student = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.sexString = @"男";
        [weakSelf.tableView reloadData];
    }];
    
    UIAlertAction * nurse = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.sexString = @"女";
        [weakSelf.tableView reloadData];
    }];
//    [nurse setValue:DV_COLOR_666666 forKey:@"titleTextColor"];
    
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    //添加各个按钮事件
    [alert addAction:student];
    [alert addAction:nurse];
    [alert addAction:cancel];
    //弹出sheet提示框
    [self presentViewController:alert animated:YES completion:nil];
}

// 行业
- (void)showProfessionAlert
{
    self.pickViewType = 1;
    [self.pickView reloadAllComponents];
}

// 地区
- (void)showDistricAlert
{
    self.pickViewType = 2;
    [self.pickView reloadAllComponents];
}

// 邮箱
- (void)showEmailAlert
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请输入您的电子邮箱" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alertController.textFields.firstObject;
        weakSelf.emailString = textField.text;
        [weakSelf.tableView reloadData];
    }]];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField*_Nonnull textField) {
        textField.placeholder=@"请输入您的电子邮箱";
    }];
    [self presentViewController:alertController animated:YES completion:nil];
}
@end
